import { Card, Checkbox, message, Select } from 'antd';
import React, { useState } from 'react';
import { Space } from 'antd';
import { CheckboxChangeEvent } from 'antd/es/checkbox';
import { GetcardNow, getRoomList } from '../request';
import { ProTable } from '@ant-design/pro-components';
import { useIntl } from '@umijs/max';
import { SetupCard } from '@/utils/Send';
interface DataType {
  roomName: any;
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
  roomId: string;
}

interface Timelist {
  label: string;
  value: number;
}

interface prpos {
  setsendMsg: (event: any) => void;
  setType: (event: string) => void;
  setGetRoomMsg: (event: any) => void;
  setgetRoomID: (event: string) => void;
  setCardMessage: (event: any) => void;
}

export const waitTimePromise = async (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export const waitTime = async (time: number = 100) => {
  await waitTimePromise(time);
};
const SetRoomcard: React.FC<prpos> = ({
  setCardMessage,
  setsendMsg,
  setType,
  setGetRoomMsg,
  setgetRoomID,
}) => {
  const intl = useIntl();

  const columns: any = [
    {
      title: intl.formatMessage({ id: 'FixLock.Building' }),
      dataIndex: 'b_name',
      key: 'b_name',
      search: false,
      align: 'center',
    },
    {
      title: intl.formatMessage({ id: 'FixLock.Floor' }),
      dataIndex: 'floor',
      key: 'floor',

      align: 'center',
    },
    {
      title: intl.formatMessage({ id: 'RoomSettings.Is suite' }),
      dataIndex: 'isSuite',
      search: false,
      render: (text: number) => {
        return <>{text == 1 ? <span style={{ color: 'green' }}>{intl.formatMessage({id:"RoomSettings.Yes"})}</span> : intl.formatMessage({id:"RoomSettings.No"})}</>;
      },
      align: 'center',
    },
    {
      title: intl.formatMessage({ id: 'RoomSettings.room' }) + ' ID',
      dataIndex: 'roomId',
      key: 'roomId',
      align: 'center',
      search: false,
    },
    {
      title: intl.formatMessage({ id: 'FixLock.Room number' }),
      dataIndex: 'roomNo',
      key: 'roomNo',
      search: false,
      align: 'center',
    },
    {
      title: intl.formatMessage({ id: 'FixLock.Room Name' }),
      dataIndex: 'roomName',
      key: 'roomName',
      align: 'center',
    },

    //
    {
      title: intl.formatMessage({ id: 'FixLock.Action' }),
      key: 'action',
      search: false,
      align: 'center',
      render: (_: any, record: DataType) => (
        <Space size="middle">
          <a onClick={() => setting(record)}>
            {intl.formatMessage({ id: 'RoomSettings.Initial setup card' })}
          </a>
          <a onClick={() => updateCard(record)}>
            {intl.formatMessage({ id: 'RoomSettings.Update settings card' })}
          </a>
          <a onClick={() => GetPowerCard(record)}>
            {intl.formatMessage({ id: 'RoomSettings.Power switch setting card' })}
          </a>
        </Space>
      ),
    },
  ];
  const GetPowerCard = async (item: DataType) => {
    if (localStorage.getItem('clientid') == '00000000')
      return message.error(intl.formatMessage({ id: 'RoomSettings.Please register' }));
    let data = {
      cardclass: 'setpowercard',
      uuid: 'setpowercard',
      setroomid: item.roomId,
      chuci: '1',
    };

    let res = await SetupCard(data);

    setCardMessage(res);

    setsendMsg(data);
    setType(`取电: ${item.roomName}设置卡成功`);
    setgetRoomID(item.roomName);
    setGetRoomMsg({
      ...data,
      ...item,
      cardType: '3',
    });
  };

  const [isTimeoutAlarmChecked, setIsTimeoutAlarmChecked] = useState(false);
  const [isFalseLockChecked, setIsFalseLockChecked] = useState(true);

  const [cardtime, setCardtime] = useState<number>(10);

  // 初发设置卡
  const setting = async (item: DataType): Promise<any> => {
    if (localStorage.getItem('clientid') == '00000000')
      return message.error(intl.formatMessage({ id: 'RoomSettings.Please register' }));

    let { data: timer } = await GetcardNow(cardtime);

    // return
    let data = {
      cardclass: 'firstsetcard',
      uuid: 'firstsetcard',
      setroomid: item.roomId,
      setlocktime: timer.now,
      setoveropen: isTimeoutAlarmChecked ? '1' : '2',
      setfalselock: isFalseLockChecked ? '1' : '2',
    };
        let res = await SetupCard(data);

    setCardMessage(res);
    setsendMsg(data);
    setType(`房号: ${item.roomName} 初发设置卡成功`);
    setgetRoomID(item.roomName);
    setGetRoomMsg({
      ...data,
      ...item,
      cardType: '1',
    });
  };

  // 更新设置卡
  const updateCard = async (item: DataType): Promise<any> => {
    if (localStorage.getItem('clientid') == '00000000')
      return message.error(intl.formatMessage({ id: 'RoomSettings.Please register' }));

    let { data: timer } = await GetcardNow(cardtime);

    let data = {
      cardclass: 'setcard',
      uuid: 'setcard',
      setroomid: item.roomId,
      setlocktime: timer.now,
      setoveropen: isTimeoutAlarmChecked ? '1' : '2',
      setfalselock: isFalseLockChecked ? '1' : '2',
    };
    let res = await SetupCard(data);
    console.log(res);
    setCardMessage(res);
    setsendMsg(data);
    setType(`房号: ${item.roomName} 更新设置卡成功`);

    localStorage.setItem('setcardType', '房卡设置卡');
    setgetRoomID(item.roomName);
    setGetRoomMsg({
      ...data,
      ...item,
      cardType: '2',
    });
  };

  const onChange = (e: CheckboxChangeEvent) => {
    setIsTimeoutAlarmChecked(e.target.checked);
  };
  const onChange2 = (e: CheckboxChangeEvent) => {
    setIsFalseLockChecked(e.target.checked);
  };

  const [timeList] = useState<Timelist[]>([]);

  for (var i = 1; i <= 60; i++) {
    if (i % 5 == 0) {
      timeList.push({
        label: i + intl.formatMessage({ id: 'RoomSettings.minute' }),
        value: i,
      });
    }
  }

  const SelectTime = (value: number) => {
    setCardtime(value);
  };

  return (
    <>
      <Card title={intl.formatMessage({ id: 'RoomSettings.Room Settings Card' })}>
        <ProTable<any>
          rowKey="id"
          defaultSize={'large'}
          columns={columns}
          cardBordered={false}
          request={async (params) => {
            await waitTime(500);
            const res: any = await getRoomList({
              ...params,
              page: params.current,
            });
            return {
              data: res.data.list || [],
              success: res.code === 0 ? true : false,
              total: res.data.totalCount,
            };
          }}
          search={{ labelWidth: 'auto' }}
          options={{
            setting: {
              listsHeight: 400,
            },
          }}
          pagination={{
            defaultPageSize: 10,
            showSizeChanger: true,
          }}
          dateFormatter="string"
          headerTitle={
            <>
              <div>
                {' '}
                {intl.formatMessage({ id: 'RoomSettings.Card access' })} : &nbsp;
                <Checkbox defaultChecked={isFalseLockChecked} onChange={onChange}>
                  {intl.formatMessage({ id: 'RoomSettings.Fake lock alarm' })}
                </Checkbox>{' '}
                &emsp;
                <Checkbox defaultChecked={isTimeoutAlarmChecked} onChange={onChange2}>
                  {intl.formatMessage({ id: 'RoomSettings.Timeout alarm' })}
                </Checkbox>{' '}
                &emsp;
              </div>

              <div>{intl.formatMessage({ id: 'RoomSettings.Delay duration' })} : &nbsp; </div>

              <Select
                defaultValue={cardtime}
                style={{ width: 160 }}
                onChange={SelectTime}
                options={timeList}
              />
            </>
          }
        />
      </Card>
      {/* <Card>

        
      </Card> */}
    </>
  );
};

export default SetRoomcard;
